package com.dgut.service.background.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dgut.service.background.config.resultConfig.JsonResult;
import com.dgut.service.background.config.resultConfig.ResultTool;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 腾讯防水墙
 */
@RestController
@RequestMapping("captcha")
public class TCaptchaVerifyController {
    private static final String APP_ID = "2067532507";
    private static final String APP_SECRET = "0csjAEkJDBEYVmAo6dqZwag**";
    private static final String VERIFY_URI = "https://ssl.captcha.qq.com/ticket/verify?aid=%s&AppSecretKey=%s&Ticket=%s&Randstr=%s&UserIP=%s";

    //防水墙验证
    @GetMapping("verify/{ticket}/{rand}")
    public String captchaVerify(@PathVariable("ticket")String ticket, @PathVariable("rand")String rand, HttpServletRequest request) throws IOException {
        String userIp = "localhost:8082";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet;
        CloseableHttpResponse response = null;
        httpGet = new HttpGet(String.format(VERIFY_URI,
                APP_ID,
                APP_SECRET,
                URLEncoder.encode(ticket, "UTF-8"),
                URLEncoder.encode(rand, "UTF-8"),
                URLEncoder.encode(userIp, "UTF-8")
        ));
        response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String res = EntityUtils.toString(entity);
//        System.out.println(res); // 临时输出
        JSONObject result = JSON.parseObject(res);
        // 返回码
        int code = result.getInteger("response");
        // 恶意等级
        int evilLevel = result.getInteger("evil_level");
        response.close();
        // 验证成功
        if (code == 1) {
            JsonResult jsonResult = ResultTool.success();
            return JSON.toJSONString(jsonResult);
        }
        JsonResult jsonResult = ResultTool.fail();
        return JSON.toJSONString(jsonResult);
    }

}
